package com.controller;

import com.util.BaseDao;
import com.util.StringUtil;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import static com.Main.changeUI;

public class Login {

    @FXML
    private TextField account;

    @FXML
    private PasswordField password;

    @FXML
    private Label errorinfo;

    @FXML
    public void initiallize(){}

    @FXML
    public void dologin(){
        String accountText = account.getText();
        String passwordText = password.getText();
        if(StringUtil.isEmpty(accountText)){
            errorinfo.setText("请输入账户！");
            errorinfo.setVisible(true);
            return;
        }
        if(StringUtil.isEmpty(passwordText)){
            errorinfo.setText("请输入密码！");
            errorinfo.setVisible(true);
            return;
        }
        //从数据库判断对错
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = BaseDao.getConn(); // 假设这个方法返回一个有效的数据库连接
            String sql = "SELECT wno, password FROM Logon WHERE wno = ? AND password = ?";
            try {
                ps = conn.prepareStatement(sql);
                ps.setString(1,accountText);
                ps.setString(2,passwordText);
               //预处理语句可以提高效率，防止SQL注入攻击使用占位符允许你使用不同的参数值来执行相同的SQL语句
                try(ResultSet rs = ps.executeQuery()){
                    if(rs.next()){
                        changeUI("ui/MainInterFace.fxml");
                        System.out.println("登录成功！");
                    }else{
                        errorinfo.setText("账号或密码错误！");
                        errorinfo.setVisible(true);
                        System.out.println("登录失败！");
                    }
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } catch (RuntimeException e) {
            throw new RuntimeException(e);
        }
    }
    @FXML
    public void doregist() {
        changeUI("ui/regist.fxml");
    }
}
